<template>
  <div class="app-container">
    <el-card class="box-card" :body-style="{ padding: '10px' }">
      <el-form :inline="true" size="mini">
        <el-form-item>
          <el-input
            v-model="listQuery.name"
            placeholder="请输入内容"
            clearable
            @keyup.enter.native="handleFilter"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click.native="handleFilter"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增角色</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="rolesList"
        border
        :key="tableKey"
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="mini"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column align="center" label="角色名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column align="center" label="角色说明">
          <template slot-scope="scope">{{ scope.row.comment }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="240px;">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              ></el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              ></el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="handleSetting(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getRoles"
      />
    </el-card>
    <!-- 角色对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑角色' : '新建角色'"
      width="40%"
    >
      <el-form
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleFormRef"
        label-width="80px"
        label-position="right"
        size="mini"
        style="padding: 0 30px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="角色名称"
            maxlength="32"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色说明" prop="comment">
          <el-input
            v-model="roleForm.comment"
            placeholder="角色说明"
            clearable
          />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" size="mini" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" size="mini" @click="SaveRole">保存</el-button>
      </div>
    </el-dialog>
    <!-- 配置权限对话框 -->
    <el-dialog
      :visible.sync="dialogTreeVisible"
      title="权限配置"
      width="35%"
      @close="treeDialogClose"
      top="30px"
    >
      <el-tree
        ref="treeRef"
        :check-strictly="checkStrictly"
        :data="permsList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        style="border: 1px solid rgb(238, 241, 246)"
      />
      <span slot="footer">
        <el-button type="danger" size="mini" @click="dialogTreeVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="SavePerms">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { roles_list, addRole, updateRole, delRole } from "@/api/roles";
import { perms_list } from "@/api/perms";
import { getParentsPath } from "@/utils/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const defaultRole = {
  id: undefined,
  name: "",
  comment: "",
  permissions: [],
};

export default {
  name: "role",
  data() {
    return {
      roleForm: Object.assign({}, defaultRole),
      roleFormRules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      dialogVisible: false,
      dialogType: "new",
      rolesList: [],

      tableKey: 0,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
      },
      // 分配权限
      dialogTreeVisible: false,
      checkStrictly: false,
      // defCheckKeys: [],
      permsList: [],
      treeProps: {
        label: "name",
        children: "children",
      },
    };
  },
  components: {
    Pagination,
  },
  created() {
    this.getRoles();
    this.getPerms();
  },
  methods: {
    getRoles() {
      this.listLoading = true;
      roles_list(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.rolesList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.listLoading = false;
        });
    },
    getPerms() {
      const params = { type: "tree" };
      perms_list(params)
        .then((res) => {
          this.permsList = res;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取权限数据失败！");
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getRoles();
    },
    // 增加权限
    handleAdd() {
      this.roleForm = Object.assign({}, defaultRole);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.roleFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.roleForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["roleFormRef"].clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该用户吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delRole(row.id);

          this.rolesList.splice($index, 1);
          this.total = this.total - 1;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 分配权限
    handleSetting(role) {
      this.roleForm = Object.assign({}, role);
      this.checkStrictly = true;
      this.dialogTreeVisible = true;
      this.$nextTick(() => {
        this.$refs.treeRef.setCheckedKeys(this.roleForm.permissions);
        this.checkStrictly = false;
      });
    },
    treeDialogClose() {
      this.$refs.treeRef.setCheckedKeys([]);
      // console.log(this.defCheckKeys)
    },
    // 保存操作
    async SaveRole() {
      this.$refs.roleFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateRole(this.roleForm);
          console.log(isEdit, res);
          const index = this.rolesList.findIndex((v) => v.id === res.id);
          this.rolesList.splice(index, 1, res);
        } else {
          const res = await addRole(this.roleForm);
          console.log(res);

          const { id } = res;
          if (id > 0) {
            this.rolesList.unshift(res);
            this.total += 1;
          }
        }

        const { name, comment } = this.roleForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>角色名称: ${name}</div>
              <div>角色说明: ${comment}</div>
            `,
          type: "success",
        });
      });
    },
    async SavePerms() {
      const checkedKeys = this.$refs.treeRef.getCheckedKeys();
      const halfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys();
      this.roleForm.permissions = [...checkedKeys, ...halfCheckedKeys];
      console.log(this.roleForm);
      updateRole(this.roleForm)
        .then((res) => {
          console.log(res);
          this.$message.success("分配权限成功！");
          this.getRoles();
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("分配权限失败！");
        });

      this.dialogTreeVisible = false;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }

  .el-tree {
    width: 95%;
    padding: 0 30px;
  }
}
</style>